<?php

namespace app\admin\controller\performance;

use app\common\controller\Backend;
use think\Db;

/**
 * 自评系统
 *
 * @icon fa fa-circle-o
 */
class Evaluation extends Backend
{
    
    /**
     * Evaluation模型对象
     */
    protected $model = null;
    protected $searchFields = 'e.month';
      /**
     * 是否开启Validate验证
     */
    protected $modelValidate = true;

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Evaluation');
        $this->evalmodel = model('Performance');

    }
    public function autoEvaluation(){
        //判断时间 每月1日0点生成 审核表
        $year = date("Y");
        $month =date("m");
        //判断是否已经生成了审核表
        $where['year'] = intval($year);
        $where['month'] = intval($month);
        $is_exist = $this->model
                    ->alias('e')
                    ->where($where)
                    ->find();
        if ($is_exist)
        {
            return;//当月已经生成了审核表
        }
        $map['status'] = 'normal';
        $alluser = model("admin")
                    ->where($map)
                    ->field("id")
                    ->select();
        $allassessment = model("assessment")
                    ->field("id")
                    ->select();
        $begin = 0;
        foreach ($alluser as $k => $v)
        {
            $performance[$k]['year'] = $year;
            $performance[$k]['month'] = $month;
            $performance[$k]['admin_id'] = $v['id'];
            $performance[$k]['datekey'] = $year.$month;
            foreach ($allassessment as $m => $n) 
            {   $begin += 1;
                //审核表数据
                $data[$begin]['year'] = $year;
                $data[$begin]['month'] = $month;
                $data[$begin]['assessment_id'] = $n['id'];
                $data[$begin]['datekey'] = $year.$month;
                $data[$begin]['admin_id'] = $v['id'];

            }
        }
        
        $this->model->saveAll($data);
        model("performance")->saveAll($performance);
        return;


    }
   
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
     /**
     * 查看
     */
    public function index()
    {   
        
        
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter  = json_decode($this->request->get("filter"),true);
            $mp  = array();
            if(!isset($filter['admin_id'])){
                $mp['admin_id'] = $this->auth->id;
            }
            if(!isset($filter['year'])){
                $mp['year'] = date('Y');
            }
            if(!isset($filter['month'])){
                $mp['month'] = date("m");
            }
            $total = $this->model
                    ->alias('e')
                    ->join('assessment a','a.id = e.assessment_id','left')
                    ->where($mp)
                    ->where($where)
                    
                    ->count();
            $list = $this->model
                    ->alias('e')
                    ->join('assessment a','a.id = e.assessment_id','left')
                    ->field("a.*,e.*")
                    ->where($mp)                  
                    ->where($where)
                   
                    ->select();        
          
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        //绩效id
        $performance_id = $this->request->get("ids");
        $where2['id'] = $performance_id;
        $performance = model("performance")->where($where2)->field("year,month,admin_id,superior_content")->find();
        if(!isset($performance))
        {   
            //如果是自评 
            $pe2['admin_id'] = $this->auth->id;
            $pe2['year'] = date('Y');
            $pe2['month'] = date("m");
            $performance = model("performance")->where($pe2)->field("year,month,admin_id,superior_content")->find();
        }
        $this->view->assign("superior_content", $performance['superior_content']);
        //对应评分详情
        if(!isset($performance['admin_id']))
        {
            
        }else
        {
            $pe['e.admin_id'] = $performance['admin_id'];
        }
        if(!isset($performance['year']))
        {
            
        }else
        {
            $pe['e.year'] = $performance['year'];
        }
        if(!isset($performance['month']))
        {
            
        }else
        {
            $pe['e.month'] = $performance['month'];
        }
          

        $admin_id = $this->auth->isLogin() ? $this->auth->id : 0;
        $usrmap['id'] = $this->request->get("admin_id")?$this->request->get("admin_id"):$this->auth->id;
        if($admin_id == $usrmap['id'])
        {
            $this->view->assign("is_self", '1');
        }else{
            $this->view->assign("is_self", '0');
        }
        $userinfo = model("admin")->where($usrmap)->find();
        $this->view->assign("year", $this->request->get("year")?$this->request->get("year"):date("Y") );
        $this->view->assign("ids", $this->request->get("ids")?$this->request->get("ids"):date("m"));
        $this->view->assign("month",$this->request->get("month")?$this->request->get("month"):date("m"));
        $this->view->assign("username",$userinfo['nickname']);
        $datail = $this->model

                        ->alias('e')
                        ->join('assessment a','a.id = e.assessment_id','left')
                        ->field("a.*,e.*")                  
                        ->where($pe)
                       
                        ->select();
        $a =  parent::getOpenStatus();
        $this->view->assign("is_open", $a);
        $this->view->assign("admin_id", $admin_id);
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {   
        $where['e.id'] = $ids;
        $row = $this->model
                ->alias('e')
                ->join('assessment a','a.id = e.assessment_id','left')
                ->field("e.*,a.*")
                ->where($where)
                ->find();

        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {  
                try
                {
                    //是否采用模型验证
                   
                    if ($this->modelValidate)
                    {   
                        
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                       
                        $row->validate($validate);
                       
                    }
                    $params['id'] = $ids;
                
                    $result = $row->allowField(true)->save($params);
                    
                   
                    if ($result !== false)
                    {   //计算平均分
                        $weight = model("weight")->where(array("id"=>'1'))->find();//权重比
                        $map2['e.id'] = $ids;
                        $info = $this->model
                                ->alias('e')
                                ->join('assessment a','a.id = e.assessment_id','left')
                                ->field("e.*,a.*")
                                ->where($map2)
                                ->find();
                        $params['ave_score'] = $info['superior_score']*$weight['superior']+$info['self_score']*$weight['junior'];
                        $result = $row->allowField(true)->save($params);

                        // foreach ($list as $key => &$value)
                        //对应 月份平均分
                        $map3['month'] = date("Y");
                        $map3['year'] = date("m");
                        $map3['admin_id'] = $info['admin_id'];
                        $monthscore = $this->evalmodel
                                    ->where($map3)
                                    ->avg("ave_score");
                        $monthself_score = $this->evalmodel
                                    ->where($map3)
                                    ->avg("self_score");
                        $monthsuperior_score = $this->evalmodel
                                    ->where($map3)
                                    ->avg("superior_score");
                        
                        $data3['self_score'] = $monthself_score;
                        $data3['superior_score']  = $monthsuperior_score;
                        $data3['ave_score']  = $monthscore;
                        $this->model->where($map3)->update($data3);
                        
           

                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $admin_id = $this->auth->id;
        if($admin_id == $row['admin_id'])
        {
            $this->view->assign("is_self", '1');
        }else
        {
            $this->view->assign("is_self", '0');
        }
        $this->view->assign("admin_id", $admin_id);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
   

}
